using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BuildingBlocks.Abstractions.Permissions;
using Identity.Application.PermissionKeyResourceIds.Interfaces;
using Identity.Application.PermissionKeyResourceIds.Queries;
using MediatR;

namespace Identity.Application.PermissionKeyResourceIds.QueryHandlers
{
    public class GetPermissionKeyResourceIdByResourceIdQueryHandler : IRequestHandler<GetPermissionKeyResourceIdByResourceIdQuery, PermissionBindingDto>
    {
        private readonly IApiPermissionBindingReadService _permissionKeyResourceIdReadService;
        public GetPermissionKeyResourceIdByResourceIdQueryHandler(IApiPermissionBindingReadService permissionKeyResourceIdReadService)
        {
             _permissionKeyResourceIdReadService= permissionKeyResourceIdReadService;
        }
        public async Task<PermissionBindingDto> Handle(GetPermissionKeyResourceIdByResourceIdQuery request, CancellationToken cancellationToken)
        {
            var permissionBinding = await _permissionKeyResourceIdReadService.GetBindingsByResourceIdAsync(request.resourceId, cancellationToken);
            if (permissionBinding == null)
            {
                throw new KeyNotFoundException($"无法找到ApiId为：{request.resourceId} 的权限绑定记录");
            }
            return permissionBinding;
        }
    }
}